package com.aj.databases.dao;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;

import com.aj.databases.DatabaseHelper;
import com.aj.databases.entry.Account;
import com.j256.ormlite.android.apptools.OpenHelperManager;
import com.j256.ormlite.dao.RuntimeExceptionDao;

public class AccountDao {

	public RuntimeExceptionDao<Account, Integer> dao = null;
	private DatabaseHelper helper = null;

	public AccountDao(Context context) {
		helper = OpenHelperManager.getHelper(context, DatabaseHelper.class);
		dao = helper.getRuntimeExceptionDao(Account.class);
	}

	public List<Account> getList(String user_id) {
		List<Account> datas = null;
		try {
			datas = dao.queryBuilder().orderBy(Account.LOGIN_TIME, true)
					.where().eq(Account.USERID, user_id).query();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return datas;
	}

	public Account get(int id) {
		Account data = null;
		data = dao.queryForId(id);
		return data;
	}

	public Account getByToken(String token) {
		Account data = null;
		try {
			List<Account> listData = dao.queryBuilder().where()
					.eq(Account.TOKEN, token).query();
			if (listData != null && listData.size() > 0) {
				data = listData.get(0);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return data;
	}

	public boolean getOneByPhoneAndUserName(String username) {
		List<Account> datas = null;
		try {
			datas = dao.queryBuilder().where().eq(Account.USERID, username)
					.query();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		if (datas != null && datas.size() > 0) {
			return true;
		} else {
			return false;
		}
	}

	public Account getOne() {
		Account data = null;
		List<Account> datas = new ArrayList<Account>();
		try {
			datas = dao.queryBuilder().orderBy(Account.LOGIN_TIME, false)
					.query();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (datas.size() > 0)
			data = datas.get(0);
		return data;
	}

	public Account insert(Account data) {
		if (data != null && data.getLast_used_user_id() != null
				&& data.getLast_used_user_id().trim().length() > 0) {
			List<Account> accountList = getList(data.getLast_used_user_id());
			if (accountList.size() > 0) {
				data.setId(accountList.get(0).getId());
				update(data);
			} else {
				return dao.createIfNotExists(data);
			}
		}
		return data;
	}

	public int update(Account data) {
		return dao.update(data);
	}

	public void del(Account data) {
		dao.delete(data);
	}

	public void delAll() {
		dao.delete(dao.queryForAll());
	}

	@Override
	protected void finalize() throws Throwable {
		OpenHelperManager.releaseHelper();// 释放掉helper
		super.finalize();
	}

}
